const path = require('path');
const { SCSS_IMPORT_REGEX, INNER_MODULE_PATH_REGEX } = require('../lib/regexUtil');
const { readFileAsync, writeFileAsync } = require('../lib/fsUtil');
const domainModulePathFix = require('../refactor/domainModulePathFix');

/**
 * 相对路径替换为src别名路径
 * @param {string} filepath
 * @param {string} fileContent
 * @param {object} opts
 * @param {string} opts.from
 * @param {string} opts.to
 */
function srcAliasPath(filepath, fileContent, opts = {}) {
  const [workDir] = filepath.split('/src/');
  const srcfullpath = workDir + '/src';
  const fpathDir = path.dirname(filepath);
  const source = fileContent;
  /*  */
  // 源码前添加一个空格是为了使正则可以捕获到全部import,因为正则中使用了反向肯定断言 ?<=\W
  // 如果不加空格， 首行 import 无法捕获
  let newSource = '\t\t\t\t' + source;

  if (filepath.includes(srcfullpath) === false) return source;

  const isCss = /\.(scss|less|css)$/m.test(filepath);

  let moduleReg = isCss ? SCSS_IMPORT_REGEX : INNER_MODULE_PATH_REGEX;

  newSource = newSource.replace(moduleReg, (raw) => {
    let len = raw.length;
    let left = raw[0];
    let mid = raw.slice(1, len - 1);
    let right = raw[len - 1];
    let srcpath = mid;
    // require(`../statics/images/${name}.png`)
    let lastSlash = mid.slice(-1) === '/' ? '/' : '';

    if (mid.startsWith('.')) {
      let newSrcpath = path.resolve(fpathDir, mid).replace(workDir + '/', '') + lastSlash;
      if (newSrcpath.startsWith('src/')) {
        srcpath = newSrcpath;
      }
    }

    // 路径规范化
    // 1. // ==> /
    // 2. src//./foo ==> src/foo
    // 3. src//foo/../bar ==> src/bar
    srcpath = path.normalize(srcpath);

    // 路径转换
    const { from, to } = opts;

    if (from && to) {
      if (srcpath === from) {
        srcpath = to;
      } else if (srcpath.startsWith(from)) {
        srcpath = srcpath.replace(appendStash(from), appendStash(to));
      } else {
        return raw;
      }
    }

    // srcpath = domainModulePathFix(srcpath);

    // TODO scss use relative path ?
    // if(isCss) {
    //   srcpath = path.relative(filepath, path.join(workDir, srcpath))
    // }

    return left + srcpath + right;
  });
  // 此处要删除首行添加的空格
  if (newSource.slice(0, 4) === '\t\t\t\t') {
    newSource = newSource.slice(4);
  }
  return newSource;
}

/** @param {string} p */
const removeLastStash = (p) => (p.slice(-1) === '/' ? p.slice(0, p.length - 1) : p);
/** @param {string} p */
const appendStash = (p) => p + '/';

/**
 *
 * @param {string} filePath
 * @param {Object} opts
 * @param {string} opts.from
 * @param {string} opts.to
 */
module.exports.transform = async (filePath, opts) => {
  if (opts && opts.from) {
    opts.from = removeLastStash(opts.from);
    opts.to = removeLastStash(opts.to);
  } else {
    opts = {};
  }

  const fileContent = await readFileAsync(filePath, { encoding: 'utf8' });
  const newContent = srcAliasPath(filePath, fileContent, opts);

  await writeFileAsync(filePath, newContent, { encoding: 'utf8' });
};

module.exports.srcAliasPath = srcAliasPath;